<?php
declare (strict_types = 1);

namespace app\controller;

use app\common\EncryptKeys;
use app\model\User;
use app\model\User as UserModel;
use think\facade\Validate;
use think\Request;
use app\common\BaseController;

class UserController extends BaseController
{

    /*
     * 登录
     */
    public function login(Request $request) {
      $data = $request->param();
      $result = Validate::rule([
        'username' => 'unique:user,username^password'
      ])->check([
        'username' => $data['username'],
        'password' => $data['password'],
      ]);

      // 获取token
      $access_token = EncryptKeys::autoSSOEncryptKen();
      $access = [
        [
          'path' => 'order',
          'name' => '订单',
          'children' => [
            [
              'name' => '订单列表',
              'path' => 'order-list'
            ]
          ]
        ],
        [
          'path' => 'show',
          'name' => '展厅',
          'children' => [
            [
              'name' => '展厅列表',
              'path' => 'show-list'
            ]
          ]
        ],
        [
          'path' => 'house',
          'name' => '仓库管理',
          'children' => [
            [
              'name' => '仓库列表',
              'path' => 'house-list'
            ],
            [
              'name' => '采购记录',
              'path' => 'purchase-list'
            ]
          ]
        ],
        [
          'path' => 'inout',
          'name' => '出入库明细',
          'children' => [
            [
              'name' => '仓库明细',
              'path' => 'house-inout-list'
            ],
            [
              'name' => '展厅明细',
              'path' => 'show-inout-list'
            ]
          ]
        ],
        [
          'path' => 'download',
          'name' => '下载表格'
        ]
      ];
      $role = UserModel::where('username', $data['username'])->find()->toArray()['role'];
      if ($role === 5) {
        $access = [
          [
            'path' => 'order',
            'name' => '订单',
            'children' => [
              [
                'name' => '订单列表',
                'path' => 'order-list'
              ]
            ]
          ]
        ];
      }
      if (!$result) {
        return $this->send200Response(['access_token' => $access_token,  'access' => $access, 'role' => $role]);
      }
      return $this->send400Response('用户名或密码错误');
    }
}
